<?php

namespace App\Http\Controllers\V1\Upload;

use App\Http\Controllers\V1\Api\RegisterHXController;
use App\Jobs\InsertDataToAdminUserJob;
use App\Jobs\RegisterToHXJob;
use App\Models\V1\AdminUser;
use App\Models\V1\Faculty;
use App\Models\V1\Role;
use Illuminate\Http\Request;
use App\Http\Requests\V1\ImportDataRequest;
use App\Models\V1\BasicFaculty;
use Maatwebsite\Excel\Facades\Excel;
use App\Events\V1\ImportExportEvent;
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Auth;

class FacultyExcelUploadController extends BaseExcelUploadController
{
    /**
     * 导入教职工数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '教职工数据导入删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);
            $filePath = $request->input('successFile');
            $fileExtension = $request->input('extension');
            //需要注册的ID
            Excel::load($filePath, function ($reader) use ($fileExtension) {
                $reader->limitColumns(9);
                //忽略空的cells
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data)->flatMap(function ($item) use ($fileExtension) {
                    $insert_data = [
                        'code' => $item[0],
                        'name' => $item[1],
                        'department_code' => $item[2],
                        'mobile' => isset($item[3]) ? $item[3] : '',
                        'telephone' => isset($item[4]) ? $item[4] : '',
                        'email' => isset($item[5]) ? $item[5] : '',
                        'title' => isset($item[6]) ? $item[6] : '',
                        'avatar' => isset($item[7]) ? $item[7] : '',
                        'specialty'=> isset($item[8]) ? $item[8] : '',
                    ];
                    if (!empty($item[0]) && !empty($item[1])) {
                        Faculty::updateOrCreate(['code' => $item[0]], $insert_data);
                        $this->registerUser($item[0]);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入[' . $request->input('successFile') . ']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));
            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出教职工数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['教职工代码', '教职工姓名', '所属部门代码', '手机号码', '办公电话', '电子邮件', '职位', '照片URL', '专业特长'];
        $custodian = Faculty::all(['code', 'name', 'department_code', 'mobile', 'telephone', 'email', 'title', 'avatar','specialty']);
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->code,
                $item->name,
                $item->department_code,
                $item->mobile,
                $item->telephone,
                $item->email,
                $item->title,
                $item->avatar,
                $item->specialty
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','教职工'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('faculty', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[教职工]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }

    //向登录的数据库表中添加数据
    private function registerUser($code){
        $insert_data = [
            'code' => $code,
            'password' => bcrypt('123456'),
            'is_staff' => 1,
        ];
        AdminUser::updateOrCreate(['code' => $code], $insert_data);
        $user = AdminUser::where('code',$code)->first();
        $role = Role::where('name','admin')->first();
        if (!$user->hasRole('admin')) {
            $user -> attachRole($role);
        }
    }
}
